package com.bysc.joinservice.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bysc.baseservice.handler.BaiYunException;
import com.bysc.commonutils.ResultCode;
import com.bysc.commonutils.Results;
import com.bysc.commonutils.constant.MessageConstant;
import com.bysc.commonutils.utils.JwtUtils;
import com.bysc.joinservice.entity.JoinDept;
import com.bysc.joinservice.entity.JoinDeptDetail;
import com.bysc.commonutils.vo.DeptVo;
import com.bysc.joinservice.entity.vo.JoinDeptAndDetailQueryVo;
import com.bysc.joinservice.entity.vo.JoinDeptQueryVo;
import com.bysc.joinservice.service.JoinDeptDetailService;
import com.bysc.joinservice.service.JoinDeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/joinservice/join-dept")
@Api(tags = "部门管理")
public class JoinDeptController {

    @Autowired
    private JoinDeptService joinDeptService;
    @Autowired
    private JoinDeptDetailService joinDeptDetailService;

    @ApiOperation(value = "新增部门（仅后台）")
    @PostMapping("addDept")
    public Results addDept(@ApiParam(name = "DeptInfo", value = "部门信息", required = true) @RequestBody JoinDept dept, HttpServletRequest request) {
        try {
            String TOKEN_clubId= JwtUtils.getClubIdByJwtToken(request);
            if(!StringUtils.isEmpty(TOKEN_clubId)){
                dept.setClubId(TOKEN_clubId);
            }
            joinDeptService.save(dept);
            return Results.ok().message(MessageConstant.ADD_DEPT_SUCCESS);
        } catch (Exception e) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.ADD_DEPT_FAIL);
        }
    }


    @ApiOperation(value = "根据id查找部门信息")
    @GetMapping("getDeptById/{id}")
    public Results getDeptById(@ApiParam(name = "id", value = "部门id", required = true) @PathVariable String id) {
        try {
            JoinDept dept = joinDeptService.getById(id);
            JoinDeptAndDetailQueryVo deptAndDetailQueryVo = new JoinDeptAndDetailQueryVo();
            if(dept!=null){
                BeanUtils.copyProperties(dept, deptAndDetailQueryVo);
            }
            LambdaQueryWrapper<JoinDeptDetail> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(JoinDeptDetail::getDeptId, id);
            JoinDeptDetail deptDetail = joinDeptDetailService.getOne(wrapper);
            if(deptDetail!=null){
                BeanUtils.copyProperties(deptDetail, deptAndDetailQueryVo);
            }
            return Results.ok().data("dept",  deptAndDetailQueryVo).message(MessageConstant.QUERY_DEPT_SUCCESS);
        } catch (Exception e) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.QUERY_DEPT_FAIL);
        }
    }

    @ApiOperation(value = "根据id修改部门信息（后台前端要传id）")
    @PutMapping("updateDeptById/{id}")
    public Results updateDeptById(@ApiParam(name = "id", value = "部门id", required = true) @PathVariable String id,
                                  @ApiParam(name = "DeptInfo", value = "修改后的部门信息", required = true) @RequestBody JoinDept updatedDept) {
        try {
            if (updatedDept != null) {
                updatedDept.setId(id);
                joinDeptService.updateById(updatedDept);
            }
            return Results.ok().message(MessageConstant.EDIT_DEPT_SUCCESS);
        } catch (Exception e) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.EDIT_DEPT_FAIL);
        }
    }

    @ApiOperation(value = "根据id删除部门（后台前端要传输id）")
    @DeleteMapping("deleteDeptById/{id}")
    public Results deleteDeptById(@ApiParam(name = "id", value = "部门id", required = true) @PathVariable String id) {
        try {
            JoinDept dept = joinDeptService.getById(id);
            if (dept != null) {
                joinDeptService.removeById(id);
                joinDeptDetailService.remove(new QueryWrapper<JoinDeptDetail>().eq("dept_id", id));
            }
            return Results.ok().message(MessageConstant.DELETE_DEPT_SUCCESS);
        } catch (Exception e) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.DELETE_DEPT_FAIL);
        }
    }

    /*
    * 新增分页查询部门
    * 可根据clubId
    * */
    @ApiOperation(value = "分页查询部门（前后台通用）")
    @PostMapping("getDeptByPage/{page}/{limit}")
    public Results getDeptByPage(@ApiParam(name = "page", value = "当前页码", required = true) @PathVariable Long page,
                                 @ApiParam(name = "limit", value = "每页记录数", required = true) @PathVariable Long limit,
                                 @ApiParam(name = "deptQuery", value = "查询对象", required = false)@RequestBody(required = false) JoinDeptQueryVo deptQuery, HttpServletRequest request)
    {
        try {
            Page<JoinDept> pageParam = new Page<>(page, limit);
            LambdaQueryWrapper<JoinDept> wrapper = new LambdaQueryWrapper<>();
            if (deptQuery != null) {
                String id = deptQuery.getId();
                String name = deptQuery.getName();
                String clubId = deptQuery.getClubId();
                if (!StringUtils.isEmpty(clubId)) {
                    wrapper.eq(JoinDept::getClubId, clubId);
                }
                else{
                    String TOKEN_clubId= JwtUtils.getClubIdByJwtToken(request);
                    if(!StringUtils.isEmpty(TOKEN_clubId)){
                        wrapper.eq(JoinDept::getClubId, TOKEN_clubId);
                    }
                }
                if (!StringUtils.isEmpty(id)) {
                    wrapper.eq(JoinDept::getId, id);
                }
                if (!StringUtils.isEmpty(name)) {
                    wrapper.like(JoinDept::getName, name);
                }
            }
            wrapper.orderByDesc(JoinDept::getSort);
            IPage<JoinDept> pageModel = joinDeptService.page(pageParam, wrapper);
            return Results.ok().data("list",pageModel).message(MessageConstant.QUERY_DEPT_SUCCESS);
        }catch (Exception e){
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.QUERY_DEPT_FAIL);
        }

    }

    /*
    * 后台 新增部门详细时候会用到
    * */
    @ApiOperation(value = "根据clubId查找所有部门（仅前台）")
    @GetMapping("getDeptByClubId")
    public Results getDeptByClubId(String clubId,HttpServletRequest request) {
        try {
            LambdaQueryWrapper<JoinDept> wrapper = new LambdaQueryWrapper<>();
            if(!StringUtils.isEmpty(clubId)){
                wrapper.eq(JoinDept::getClubId, clubId);
            }
            else{
                String TOKEN_clubId = JwtUtils.getClubIdByJwtToken(request);//token解析clubId
                if (!StringUtils.isEmpty(TOKEN_clubId)) {
                    wrapper.eq(JoinDept::getClubId, TOKEN_clubId);
                }
            }
            wrapper.orderByDesc(JoinDept::getSort);
            List<JoinDept> depts = joinDeptService.list(wrapper);
            return Results.ok().data("depts", depts).message(MessageConstant.QUERY_DEPT_SUCCESS);
        } catch (Exception e) {
            throw new BaiYunException(  ResultCode.ERROR, MessageConstant.QUERY_DEPT_FAIL);
        }
    }

//    @ApiOperation(value = "查找所有部门")
//    @Cacheable(value = "index", key = "'dept'")
//   //@GetMapping("getAllDepts")
//    public Results getAllDepts() {
//        try {
//            List<JoinDept> depts = joinDeptService.list(new QueryWrapper<JoinDept>().orderByDesc("sort"));
//            return Results.ok().data("depts", depts).message(MessageConstant.QUERY_DEPT_SUCCESS);
//        } catch (Exception e) {
//            throw new BaiYunException(ResultCode.ERROR, MessageConstant.QUERY_DEPT_FAIL);
//        }
//    }

    @ApiOperation(value = "根据clubId查找对应部门以及详情（仅后台）")
    @GetMapping("getDeptInfoByClubId")
    public Results getDeptInfoByClubId(HttpServletRequest request) {
        try {
            List<JoinDept> depts = (List<JoinDept>) getDeptByClubId(null,request).getData().get("depts");
            ArrayList<DeptVo> list = new ArrayList<>();
            for (JoinDept dept : depts) {
                DeptVo deptVo = new DeptVo();
                JoinDeptDetail deptDetail = joinDeptDetailService.getOne(new QueryWrapper<JoinDeptDetail>().eq("dept_id", dept.getId()));
                if(deptDetail!=null){
                    BeanUtils.copyProperties(dept, deptVo);
                    BeanUtils.copyProperties(deptDetail, deptVo);
                    list.add(deptVo);
                }
            }
            return Results.ok().data("depts", list).message(MessageConstant.QUERY_DEPT_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.QUERY_DEPT_FAIL);
        }
    }

}
